//
//  DDScanController.m
//  DDMusic
//
//  Created by 何星宏 on 2016/11/15.
//  Copyright © 2016年 FengBaoFamily. All rights reserved.
//

#import "DDScanController.h"
#import <AVFoundation/AVFoundation.h>
#import <Masonry.h>
#import <BlocksKit.h>
#import <BlocksKit+UIKit.h>
#import "DDLSJHdManager.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [[UIScreen mainScreen]bounds].size.height

@interface DDScanController () <AVCaptureMetadataOutputObjectsDelegate>{
    AVCaptureSession* _session;
    AVCaptureVideoPreviewLayer* _layer;
    UIView* _codeView;
    UITextView* _textView;
}

@end

@implementation DDScanController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSubViews];
    [self getQRCodeInfo];

}
- (void)createSubViews {
    
    _codeView = [[UIView alloc] init];
    _codeView.backgroundColor = [[UIColor orangeColor] colorWithAlphaComponent:0.3];
    [self.view addSubview:_codeView];
    
    [_codeView  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view.mas_centerY).offset(-kScreenHeight*0.2);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth*0.7, kScreenWidth*0.7));
    }];
    
    _textView = [[UITextView alloc] init];
    _textView.font = [UIFont systemFontOfSize:15];
    _textView.layer.cornerRadius = 5;
    _textView.layer.masksToBounds = YES;
    [self.view addSubview:_textView];
    {
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(_codeView.mas_bottom).offset(20);
            make.size.mas_equalTo(CGSizeMake(kScreenWidth*0.9, 80));
        }];
    }
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundColor:[UIColor cyanColor]];
    [btn setTitle:@"开始扫描" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:30];
    btn.layer.cornerRadius = 5;
    btn.layer.masksToBounds = YES;
    [self.view addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-kScreenHeight*0.1);
        make.size.mas_equalTo(CGSizeMake(150, 50));
    }];
    
    [btn bk_addEventHandler:^(id sender) {
        if (!_session.isRunning) {
            [_session startRunning];
        }
    } forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *push = [UIButton buttonWithType:UIButtonTypeCustom];
    [push setBackgroundColor:[UIColor yellowColor]];
    [push setTitle:@"在网页中打开" forState:UIControlStateNormal];
    [push setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    push.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    push.layer.cornerRadius = 5;
    push.layer.masksToBounds = YES;
    [self.view addSubview:push];
    
    [push mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_textView.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(200, 50));
    }];
    
    [push bk_addEventHandler:^(id sender) {
        if (![_textView.text isEqualToString:@""]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_textView.text]];
        }
    } forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)getQRCodeInfo {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    _session = [[AVCaptureSession alloc] init];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if (input) {
        [_session addInput:input];
    }
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    [_session addOutput:output];
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
    _layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer insertSublayer:_layer above:0];
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    _layer.frame = _codeView.frame;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    NSString *zhQRCode = nil;
    for (AVMetadataObject *metadata in metadataObjects) {
        if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {
            zhQRCode = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
            break;
        }
    }
    [[DDLSJHdManager manager]showHuaWithText:zhQRCode];
    _textView.text = zhQRCode;
    
    [_session stopRunning];
}




@end
